package com.winning.dps.ds.config;


import com.winning.dps.ds.service.common.TokenService;
import common.entity.TokenEntity;
import common.exception.BaseException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @Author: nxs@winning.com.cn
*
* @Description:   权限(Token)验证
*
* @Date:  2018-06-27 16:58:39
*
*
 **/
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private TokenService tokenService;

    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        //token为空
        if(StringUtils.isBlank(token)){
            throw new BaseException("token不能为空");
        }

        //查询token信息
        TokenEntity tokenEntity = tokenService.queryByToken(token);
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new BaseException("token失效，请重新登录");
        }

        //设置用户主键-注册流水号到request里，后续根据zclsh，获取用户信息
        request.setAttribute(LOGIN_USER_KEY, tokenEntity.getZclsh());

        return true;
    }
}
